/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.factory.ctrl;


import com.alibaba.fastjson.JSON;
import com.pitop.core.entity.BeanRet;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.JwtToken;
import com.pitop.factory.entity.Factory;
import com.pitop.factory.service.FactorySVImpl;
import com.pitop.setting.entity.Setting;
import com.pitop.setting.service.SettingSVImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 工厂管理 控制器
 *
 * @author pi-top
 */
@RestController
@RequestMapping("/factory")
@Slf4j
@Api(value = "工厂管理控制器", description = "工厂管理控制器")
public class FactoryCtrl {

    @Autowired
    private FactorySVImpl factorySVImpl;

    @Autowired
    private SettingSVImpl settingSVImpl;


    /**
     * 根据条件code查询Factory一个详情信息
     *
     * @param code 工厂编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询Factory一个详情信息", notes = "查询Factory一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "工厂编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/token/{code}")
    @ResponseBody
    public BeanRet token(@PathVariable String code) {
        if (StringUtils.isEmpty(code)) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        Factory factory = factorySVImpl.loadByCode(code);
        if (factory == null) {
            return BeanRet.create(false, BaseException.BaseExceptionEnum.Result_Not_Exist);
        }

        Setting syncExpireTimeSetting = settingSVImpl.loadByK(Setting.Key.SyncExpireTime.name());
        long syncExpireTime = Long.parseLong(syncExpireTimeSetting.getV());
        Setting token_SecretSetting = settingSVImpl.loadByK(Setting.Key.Token_Secret.name());
        String token_Secret = token_SecretSetting.getV();

        String token = JwtToken.createToken(token_Secret, syncExpireTime); //生成token

        log.info(JSON.toJSONString(factory));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, token);
    }

}
